import React, { useState, useEffect } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import logo from '../../../images/logo.svg'
import style from './register.module.scss'
import validator from 'validator'
import { IRegister, useSignUpMutation } from '../../../starter/api/authApi'


type TRegister = {
}
function Register({}: TRegister) {
  const navigate = useNavigate()
  const [formData, setFormData] = useState<IRegister>({name: '', email: '', password: '', accessLevel: 'user'})
  const [formErrors, setFormErrors] = useState({name: '', email: '', password: '', accessLevel: ''})
  const [isSubmitting, setIsSubmitting] = useState(false)

  const [addUser, {isLoading, isError, error, isSuccess}] = useSignUpMutation()
  const isFormValid = () => {
    return (
      Object.values(formData).every(value => value !== '') &&
      Object.values(formErrors).every(error => error === '') &&
      !isSubmitting
    )
  }
  useEffect(() => {
    if (isSuccess) {
      navigate('/signin')
    }
  }, [isSuccess])

  const handleInputChange = (evt: React.ChangeEvent<HTMLInputElement>): void => {
    const { name, value } = evt.target
    setFormData({
      ...formData,
      [name]: value,
    })

    validateField(name, value)
  }

  const validateField = (fieldName:string, value:string) => {
    let errorMessage = ''

    switch (fieldName) {
      case 'name':
        if (value.length < 5) {
          errorMessage = 'Имя должно содержать не менее двух символов'
        } else if (!validator.matches(value, /^[0-9-A-Za-zА-Яа-яЁё\s-]{2,30}$/)) {
          errorMessage = 'Имя должно содержать только латиницу, кириллицу, пробел, дефис или цифры'
        }
        break
      case 'email':
        if (value.length < 5) {
          errorMessage = 'Email должен содержать от 5 до 30 символов'
        } else if (!validator.isEmail(value)) {
          errorMessage = 'Введите корректный email'
        }
        break
      case 'password':
        if (!validator.isLength(value, { min: 5, max: 40 })) {
          errorMessage = 'Пароль должен содержать от 5 до 40 символов'
        }
        break
      case 'accessLevel':
        if (!validator.isLength(value, { min: 3, max: 40 })) {
          errorMessage = 'установить accessLevel'
        }
        break
      default:
        break
    }

    setFormErrors({
      ...formErrors,
      [fieldName]: errorMessage,
    })
  }

  async function handleSubmit(evt: React.FormEvent<HTMLFormElement>): Promise<void> {
    evt.preventDefault()

    if (isFormValid() && !isSubmitting) {
      setIsSubmitting(true)
      try {
        addUser(formData)
      } catch (err) {
        console.log(err)
      } finally {
        setIsSubmitting(false)
      }
    }
  }

  return (
    <>
      <section className={style.register}>
        <Link to='/'>
          <img src={logo} alt='Логотип' className={style.register__logo} />
        </Link>
        <main className={style.register__content}>
          <h1 className={style.register__title}>Добро пожаловать!</h1>
          <form className={style.register__form} onSubmit={handleSubmit}>
            <label className={style.register__label}>
              Имя
              <input
                className={style.register__input}
                name='name'
                type='text'
                placeholder='Имя'
                minLength={ 5 }
                maxLength={ 40 }
                autoComplete='off'
                required
                value={formData.name}
                onChange={handleInputChange}
              />
              <span className={`${formErrors.name ? 'register__input-error' : ''}`}>{formErrors.name}</span>
            </label>
            <label className={style.register__label}>
              E-mail
              <input
                className={style.register__input}
                name='email'
                type='email'
                placeholder='E-mail'
                minLength={ 5 }
                maxLength={ 40 }
                autoComplete='off'
                required
                value={formData.email}
                onChange={handleInputChange}
              />
              <span className={`${formErrors.email ? style['register__input-error'] : ''}`}>{formErrors.email}</span>
            </label>
            <label className={style.register__label}>
              Пароль
              <input
                className={style.register__input}
                name='password'
                type='password'
                placeholder='Пароль'
                minLength={ 5 }
                maxLength={ 40 }
                autoComplete='off'
                required
                value={formData.password}
                onChange={handleInputChange}
              />
              <span className={`${formErrors.password ? style['register__input-error'] : ''}`}>{formErrors.password}</span>
            </label>
            {isError && <p className={style['register__error-message']}>{JSON.parse(JSON.stringify(error)).data.message}</p>}
            <button className={`register__button ${!isFormValid() ? style.register__button_disabled : ''}`}
              type='submit'
              disabled={!isFormValid() || isLoading}
              >
              Зарегистрироваться
            </button>
          </form>
          <p className={style.register__text}>
            Уже зарегистрированы?{' '}
            <Link className={style.register__link} to='/signin'>
              <span className={style.register__signin}>Войти</span>
            </Link>
          </p>
        </main>
      </section>
    </>
  )
}

export default Register
